import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../../../core/providers/discussion_hub_provider.dart';
import '../../../core/models/question.dart';
import 'package:qilo/core/constants/app_colors.dart';
import 'package:qilo/core/constants/app_icons.dart';
import 'question_answer_page.dart';
import 'community_question_creation_page.dart';

class MusicHelpHubPage extends StatelessWidget {
  const MusicHelpHubPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _buildAppBar(context),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      SizedBox(height: 20.h),
                      _buildWelcomeCard(),
                      SizedBox(height: 24.h),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Consumer<DiscussionHubProvider>(
                          builder: (context, discussionProvider, child) {
                            if (discussionProvider.isDataLoading) {
                              return Container(
                                height: 200.h,
                                child: const Center(
                                  child: CircularProgressIndicator(),
                                ),
                              );
                            }

                            if (discussionProvider.errorMessage != null) {
                              return Container(
                                height: 200.h,
                                child: Center(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.error_outline,
                                        size: 48.w,
                                        color: Colors.grey,
                                      ),
                                      SizedBox(height: 16.h),
                                      Text(
                                        'Failed to load discussions',
                                        style: TextStyle(
                                          fontSize: 16.sp,
                                          color: Colors.grey[600],
                                        ),
                                      ),
                                      SizedBox(height: 8.h),
                                      ElevatedButton(
                                        onPressed: () {
                                          discussionProvider.refreshData();
                                        },
                                        child: const Text('Retry'),
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            }

                            final topics = discussionProvider.topicCollection;
                            if (topics.isEmpty) {
                              return Container(
                                height: 200.h,
                                child: Center(
                                  child: Text(
                                    'No discussions available',
                                    style: TextStyle(
                                      fontSize: 16.sp,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ),
                              );
                            }

                            return Column(
                              children: [
                                ...topics
                                    .map(
                                      (topic) => Column(
                                        children: [
                                          _buildQuestionCard(topic: topic),
                                          SizedBox(height: 16.h),
                                        ],
                                      ),
                                    )
                                    .toList(),
                                SizedBox(height: 100.h),
                              ],
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAppBar(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(Icons.arrow_back_ios, color: Colors.white, size: 24.w),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Music Help Hub',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                  fontFamily: 'Poppins',
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () => _navigateToCreateQuestion(context),
            child: Icon(MyIcons.iconSend2, color: Colors.white, size: 22.w),
          ),
        ],
      ),
    );
  }

  Widget _buildWelcomeCard() {
    return AspectRatio(
      aspectRatio: 375 / 169,
      child: Container(
        width: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/help-top.png'),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  Widget _buildQuestionCard({required DiscussionTopic topic}) {
    return Builder(
      builder:
          (context) => GestureDetector(
            onTap: () => _navigateToAnswerPage(context, topic),
            child: Container(
              width: double.infinity,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/question-bg.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: Container(
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Hero(
                      tag: 'question_title_${topic.topicId}',
                      child: Material(
                        color: Colors.transparent,
                        child: Text(
                          topic.topicTitle,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 12.sp,
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.w500,
                            height: 1.5,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Row(
                      children: [
                        Text(
                          '${topic.responseCount} Answers',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.grey[600],
                            fontFamily: 'Poppins',
                          ),
                        ),
                        SizedBox(width: 16.w),
                        Text(
                          '${topic.viewerCount} Views',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.grey[600],
                            fontFamily: 'Poppins',
                          ),
                        ),
                        const Spacer(),

                        Row(
                          children: [
                            Icon(MyIcons.iconEdit2, color: AppColors.iconColor),
                            SizedBox(width: 2.w),
                            Text(
                              'Write An Answer',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: AppColors.iconColor,
                                fontFamily: 'Poppins',
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
    );
  }

  void _navigateToAnswerPage(
    BuildContext context,
    DiscussionTopic topic,
  ) async {
    // 增加浏览量
    context.read<DiscussionHubProvider>().incrementTopicViews(topic.topicId);

    final result = await Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => QuestionAnswerPage(topic: topic)),
    );

    // 如果返回值为 true，表示需要刷新列表
    if (result == true && context.mounted) {
      // 刷新 DiscussionHubProvider 数据
      final discussionProvider = context.read<DiscussionHubProvider>();
      discussionProvider.refreshData();
    }
  }

  void _navigateToCreateQuestion(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const CommunityQuestionCreationPage(),
      ),
    );
  }
}
